import { ref, onMounted, onUnmounted } from 'vue'
import dayjs from 'dayjs'

export function useCountdown(targetTime: number) {
  const days = ref(0)
  const hours = ref(0)
  const minutes = ref(0)
  const seconds = ref(0)

  let intervalId: any = null

  const updateCountdown = () => {
    const now = dayjs().valueOf()
    const diff = targetTime - now

    if (diff <= 0) {
      clearInterval(intervalId)
      return
    }

    days.value = Math.floor(diff / (1000 * 60 * 60 * 24))
    hours.value = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
    minutes.value = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
    seconds.value = Math.floor((diff % (1000 * 60)) / 1000)
  }

  updateCountdown()
  // console.log(days.value, hours.value, minutes.value, seconds.value)
  // onUnmounted(() => {
  //   if (intervalId) {
  //     clearInterval(intervalId)
  //   }
  // })

  return { days, hours, minutes, seconds }
}
